<template>
  <div>
    <el-button @click="drawer = true" type="info" plain style="margin: 10px 10px">查看日志</el-button>
    <el-button v-if="canModify(paper_info.permissionId)" type="success" @click="modifyExamPaper()">{{modifyButtonVisible?'修改完成':'修改试卷'}}</el-button>
    <!-- 导出按钮 -->
    <el-button v-if="!modifyButtonVisible" style="width: 100px;height:40px">
      <el-dropdown @command="handleCommand" trigger="click" placement="bottom-start">
        <span class="el-dropdown-link">导出<i class="el-icon-arrow-down el-icon--right"></i></span>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item v-print="printObj">导出pdf</el-dropdown-item>
          <el-dropdown-item command='1' @click="exportWord()">导出word(只包含文字且带有html格式)</el-dropdown-item>
          <el-dropdown-item command='2' @click="exportWord2()">导出word(推荐)</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </el-button>
    <!-- 修改试卷相关的四个按钮 -->
    <div v-if="modifyButtonVisible" style="padding:0 20px;margin: 0px 8px;display:inline-block">
        <el-button type="primary" @click="dialogFormVisible = true;cForm = {};" v-if="disabled">添加题目</el-button>
        <el-button type="warning" plain @click="changeLocation()" v-if="disabled">调整位置</el-button>
        <el-button type="warning" plain  @click="confirmLocation()" v-if="!disabled">确定位置</el-button>
    </div>
    <el-button   type="success" plain  @click="SubmitForApproval" v-if="(paper_info.permissionId==1)&&(!modifyButtonVisible)" >提交审核</el-button>

    
    <!-- 添加题目的对话框 -->
    <el-dialog :visible.sync="dialogFormVisible" width="65%" >
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <!-- 自定义添加直接仿照题库中添加题目的样子 -->
          <el-tab-pane label="自定义试题" name="first" >
            <div >
              <el-form :inline="true" :model="cForm" ref="cForm" label-width="80px">
                <el-form-item label="题目类型" label-width="100px">
                  <el-select placeholder="请选择" v-model="cForm.type" clearable>
                    <el-option :label="c1.type" :value="c1.id" v-for="(c1, index) in typeList" :key="c1.id"></el-option>
                  </el-select>
                </el-form-item>

                <el-form-item label="题目分值" label-width="100px" prop="score" style="width:300px">
                    <el-input  autocomplete="off" v-model="cForm.score"></el-input>
                </el-form-item>

                <el-form-item label="题干描述" label-width="100px">
                  <div id="questionContent">
                    <vue-tinymce v-model="cForm.name" :setting="setting" />
                  </div>
                </el-form-item>

                <el-form-item label="题目答案" label-width="100px">
                  <el-input v-show="cForm.type==='1'||cForm.type==='2'" placeholder="请输入内容" v-model="cForm.answer"></el-input>
                  <div v-show="cForm.type==='3'">
                    <el-radio v-model="cForm.answer" label="对">对</el-radio>
                    <el-radio v-model="cForm.answer" label="错">错</el-radio>
                  </div>
                  <div id="questionContent" v-show="!(cForm.type==='1'||cForm.type==='2'||cForm.type==='3')">
                    <vue-tinymce v-model="cForm.answer" :setting="setting" />
                  </div>
                </el-form-item>

              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="addOneQuestion(cForm)">确 定</el-button>
              </div>
            </div> 
          </el-tab-pane>
          <el-tab-pane label="从题库导入" name="second" >
            <questionManagement visible="true" @listenEvent="getListenEvent"/>
          </el-tab-pane>
          <el-tab-pane label="智能组卷" name="third" >
            <!-- 智能组卷对话框 -->
            <el-form  :model="intellectualExam" ref="intellectualExam" label-width="80px">
              <el-row>
                <el-col span="8">
                  <el-form-item label="题型" label-width="90px" prop="type" required>
                    <el-select placeholder="请选择" v-model="intellectualExam.type" >
                      <el-option :label="c1.type" :value="c1.id" v-for="(c1, index) in typeList" :key="c1.id"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col span="8">
                  <el-form-item label="分值" label-width="90px" prop="score" required>
                    <el-input style="width:200px" v-model="intellectualExam.score" clearable></el-input>
                  </el-form-item>
                </el-col>
                <el-col span="8">
                  <el-form-item label="数量" label-width="90px" prop="number" required>
                    <el-input style="width:200px" v-model="intellectualExam.number" clearable></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col span="8">
                  <el-form-item label="专业" label-width="90px" prop="major" >
                    <el-select
                      v-model="intellectualExam.major"
                      multiple
                      collapse-tags
                      placeholder="请选择">
                      <el-option :label="c1.major" :value="c1.id" v-for="(c1, index) in majorList" :key="c1.id"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col span="8">
                  <el-form-item label="科目" label-width="90px" prop="subject" >
                    <el-select
                      v-model="intellectualExam.subject"
                      multiple
                      collapse-tags
                      placeholder="请选择">
                      <el-option :label="c1.subject" :value="c1.id" v-for="(c1, index) in subjectList" :key="c1.id"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col span="8">
                  <el-form-item label="题库" label-width="90px" prop="storeIds" >
                    <el-select
                      v-model="intellectualExam.storeIds"
                      multiple
                      collapse-tags
                      placeholder="请选择">
                      <el-option :label="c1.name" :value="c1.id" v-for="(c1, index) in questionKuList" :key="c1.id"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item label="难度等级" label-width="100px">
                <el-radio-group v-model="level">
                  <el-radio :label="1">难度等级选择</el-radio>
                  <el-radio :label="2">难度等级区间</el-radio>
                </el-radio-group>
              </el-form-item>

              <el-row v-show="level==1">
                <el-form-item label="难度等级" >
                  <el-select
                    style="width:300px"
                    v-model="intellectualExam.levelBetween"
                    multiple
                    filterable
                    allow-create
                    default-first-option
                    placeholder="请选择难度">
                  <el-option :label="c1" :value="c1" v-for="(c1, index) in levelList" :key="c1"></el-option>
                  </el-select>
                </el-form-item>

              </el-row>
              <el-row v-show="level==2">
                <el-col span="8">
                  <el-form-item label="下限" label-width="50px" prop="levelInterval.down" >
                    <el-select placeholder="请选择" v-model="intellectualExam.levelInterval.down" clearable>
                      <el-option :label="c1" :value="c1" v-for="(c1, index) in levelList" :key="c1"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col span="8">
                  <el-form-item label="上限" label-width="50px" prop="levelInterval.up" >
                    <el-select placeholder="请选择" v-model="intellectualExam.levelInterval.up" clearable>
                      <el-option :label="c1" :value="c1" v-for="(c1, index) in levelList" :key="c1"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-button plain type="success" @click="addItem()">添加类型</el-button>
              <el-table :data="intellectualExamList" align="center">
                <el-table-column prop="type" label="题型"/>
                <el-table-column prop="number" label="数量"/>
                <el-table-column prop="score" label="分数"/>
                <el-table-column prop="major" label="科目">
                  <template slot-scope="scope">
                    <span>{{showMajor(scope.row.major)}}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="subject" label="科目">
                  <template slot-scope="scope">
                    <span>{{showSubject(scope.row.subject)}}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="storeIds" label="个人题库">
                  <template slot-scope="scope">
                    <span>{{showStores(scope.row.storeIds)}}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="levelBetween" label="难度等级">
                   <template slot-scope="scope">
                    <span>{{showLevelBetween(scope.row)}}</span>
                  </template>                
                </el-table-column>
                <el-table-column prop="levelInterval" label="难度范围">
                   <template slot-scope="scope">
                    <span v-if="scope.row.level==2">[{{scope.row.levelInterval.down}}-{{scope.row.levelInterval.up}}]</span>
                    <span v-if="scope.row.level==1">null</span>
                  </template> 
                </el-table-column>
                <el-table-column
                  fixed="right"
                  label="操作"
                  width="120">
                  <template slot-scope="scope">
                    <el-button
                      @click.native.prevent="deleteRow(scope.$index, intellectualExamList)"
                      type="text"
                      size="small">
                      移除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-button type="warning" plain @click="intelligentPaper()">确定导入</el-button>
            </el-form>
    
          </el-tab-pane>
        </el-tabs>
    </el-dialog>

    <!-- 选中题目之后，导入题目之前的对话框 -->
    <el-dialog :visible.sync="selectQuestionVisible" width="80%">
      <div>
        <el-table border :data="selectedQuestions" >
          <el-table-column width="200px" prop="type" label="题目类型" align="center" />
          <el-table-column label="题目内容" align="center" >
            <template slot-scope="scope">
              <span v-html="scope.row.name"/>
            </template>
          </el-table-column>
          <el-table-column prop="score" width="100px" label="题目分值" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.score" value="scope.row.score" ></el-input>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div>
        <el-button type="warning" plain style="float:right;margin: 10px 20px" @click="addSelectedQuestions">确定导入</el-button>
      </div>
    </el-dialog>

    <!-- 修改题目的弹出框 -->
    <el-dialog :visible.sync="modifyVisible" width="80%" >
      <div >
        <el-form :inline="true" :model="cForm" ref="cForm" label-width="80px">
          <el-form-item label="题目类型" label-width="100px">
            <el-select placeholder="请选择" v-model="cForm.type" clearable>
              <el-option :label="c1.type" :value="c1.id" v-for="(c1, index) in typeList" :key="c1.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="题目分值" label-width="100px" prop="score" style="width:300px">
              <el-input  autocomplete="off" v-model="cForm.score"></el-input>
          </el-form-item>

          <!-- <el-form-item label="题目位置" label-width="100px" prop="position" style="width:300px">
              <el-input  autocomplete="off" v-model="cForm.location"></el-input>
          </el-form-item> -->

          <el-form-item label="题干描述" label-width="100px">
            <div id="questionContent">
              <vue-tinymce  v-model="cForm.name" :setting="setting" ></vue-tinymce>
            </div>
          </el-form-item>

          <!-- <el-form-item label="题目答案" label-width="100px">
            <el-input v-show="cForm.type==='1'||cForm.type==='2'" placeholder="请输入内容" v-model="cForm.answer"></el-input>
            <div v-show="cForm.type==='3'">
              <el-radio v-model="cForm.answer" label="对">对</el-radio>
              <el-radio v-model="cForm.answer" label="错">错</el-radio>
            </div>
            <div id="questionContent" v-show="!(cForm.type==='1'||cForm.type==='2'||cForm.type==='3')">
              <vue-tinymce v-model="cForm.answer" :setting="setting" ></vue-tinymce>
            </div>
          </el-form-item> -->
          <el-form-item label="题目答案" label-width="100px">
            <div v-show="cForm.type==='1'||cForm.type==='2'">
              选择题答案只能输入大写字母
              <el-input v-if="cForm.type==='1'" placeholder="请输入内容" v-model="cForm.answer" onkeypress="return(/[A-Z]/.test(String.fromCharCode(event.keyCode)))"></el-input>
              <el-input v-else-if="cForm.type==='2'" placeholder="请输入内容" v-model="cForm.answer" onkeypress="return(/[A-Z]/.test(String.fromCharCode(event.keyCode)))"></el-input>
            </div>
            <div v-show="cForm.type==='3'"> 
              <el-radio v-model="cForm.answer" label="对">对</el-radio>
              <el-radio v-model="cForm.answer" label="错">错</el-radio>
            </div>
            <div v-show="!(cForm.type==='1'||cForm.type==='2'||cForm.type==='3')" class="filter-container">
              <el-button class="filter-item" type="primary" icon="el-icon-plus" size="small" plain @click="addAnswer">
                添加
              </el-button>
              <el-table :data="this.answerList" :border="true" style="width: 100%;">
                <el-table-column label="答案内容" width="800px">
                  <template slot-scope="scope">
                    <vue-tinymce v-model="scope.row.content" :setting="setting2" />
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="100px">
                  <template slot-scope="scope">
                    <el-button type="danger" icon="el-icon-delete" circle @click="removeAnswerItem(scope.$index)" />
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="modifyQuestion(cForm)">确 定</el-button>
        </div>
      </div> 
    </el-dialog>

  <!-- 展示试卷所有题目 -->
  <div id="pdf" style="padding: 10px 5%" class="box-card">
    <h2 align="center">{{paper_info.name}}(总分值：{{totalScore}})</h2>
    <span style="text-align: center;display:block;">标注：{{paper_info.remark}}</span>
    <div v-for = "(questions,qType ,i) in allQuestionThisPaper" :key="i" >
        <hr>
        <h4>{{questionType(qType)}}</h4>
        <draggable v-model="allQuestionThisPaper[qType]" :disabled="disabled" chosenClass="chosen" forceFallback="true" :group="i" animation="500">
            <transition-group>
              <!-- <div class="item" v-for="element in myArray" :key="element.id">{{element.name}}</div> -->
              <div class="item" v-for="(q,j) in questions" :key="j" style="padding: 10px 20px">
                <el-card >
                    <el-divider><span style="color: rgb(239,160,48)">(分值：{{q.score}})</span></el-divider>
                
                    <el-button v-if="modifyButtonVisible" @click="deleteQuestion(q.id)"  style= "float: right;padding: 5px 5px"  type="danger" icon="el-icon-delete" circle></el-button>
                    <el-button v-if="modifyButtonVisible" @click="updateAllow(q)" style= "float: right; padding: 5px 5px; margin:0 5px" type="warning" plain>修改题目</el-button>

                    <span>{{j+1}}、</span>
                    <span class="title" v-html="q.name"></span>
                    
                    <span>答案：</span>
                    <!-- <span v-html="q.answer"></span> -->
                    <div v-for="(ans,index) in q.answer.split('duang')" :key='index'>
                      <span v-html="ans"></span>
                    </div>

                    <!-- <el-button v-if="locationVisible" @click="moveUp(q.type,j)"  style= "float: right;padding: 5px 5px" icon="el-icon-caret-top" circle></el-button>
                    <el-button v-if="locationVisible" @click="moveDown(q.type,j)" style= "float: right; padding: 5px 5px; margin:0 5px" icon="el-icon-caret-bottom" circle></el-button> -->

                </el-card >
              </div>
            </transition-group>
        </draggable>

    </div>

  </div>

  <!-- 展示试卷的日志 -->
  <el-drawer
    size="40%"
    title="日志"
    :visible.sync="drawer"
    :direction="direction">
      <ul class="infinite-list">
        <li v-for="(log,i) in paperLog" :key="i">{{log.gmtCreate}}{{log.info}}</li>
      </ul>
  </el-drawer>
  </div>
</template>

<script>
import draggable from 'vuedraggable'
import questionManagement from "../question_management/index.vue";

// 以下是导出word--模板需要的库
import JSZipUtils from 'jszip-utils'
// import JSZip from 'jszip'
import JSZip from 'pizzip'
import Docxtemplater from 'docxtemplater'
import { saveAs } from 'file-saver'

// 以下导出word--数据流需要的库
import $ from 'jquery'
require('./js/jquery.wordexport')

export default {
    name:'one_exam_paper',
    components:{
      questionManagement,
      draggable
    },
    mounted(){
        this.paper_info = JSON.parse(this.$route.query.paper_info);
        this.getPageList();
        this.getTypeList();
        // 获取登陆者的姓名
        this.lander =  this.$store.getters.name;
        this.getMajorList();
        this.getSubjectList();
        this.getQuestionKuList();
    },
    data() {
        return {
          
          inputVisible: false,
          inputValue: '',


          totalScore:0,//总分数
          modifyButtonVisible:false,//试卷修改几个相关按钮可见性
          level:1,
          intellectualExam:{
            type:'',
            number:0,//题目的数量
            score:0,//分数
            major:null,//专业
            subject:null,//科目
            storeIds:null,//个人题库
            level:1,
            levelBetween:null,
            levelStartEnd:null,
            levelInterval:{down:'',up:''},
          },
          intellectualExamList:[],
          printObj: {
            id: 'pdf',
          },
          disabled:true,//设置可以调整位置的选项
          // locationVisible:false, //调整位置的显示

          lander:'',  //目前登陆者的姓名
          // 日志相关
          drawer: false,
          direction: 'rtl',

          // 对话框相关
          dialogVisible: false,
          dialogFormVisible:false,
          activeName: 'second',
          modifyVisible: false,//修改题目时的对话框
          selectQuestionVisible:false,//确定导入题目的对话框
          paper_info:{
          id: "",
          name: "",
          status:"",
          remark: "",
          statusName:"",
          isDeleted:'' ,
          gmtCreate:"",
          gmtModified:"",
          permissionId:"",
          permissionName:""
          },
          cForm:{
          id:'',
          name:'',
          answer:'',
          score:'',
          location:'',//处在题目中的位置
          paperId:'',//试卷的id
          type:'',//问题的种类，是填空题还是。。。
          version:0
          },
          answerList:[],
          // 在图库选中的题目
          selectedQuestions:[],
          mark:'',  //标记题目是来自总体库还是私人题库

          // 试卷所有题目
          allQuestionThisPaper:{}, //获得的是一个对象名。key对应了题目类型表示。如1是选择题

          paperLog:[ ],

          //         
          checkAll: false,

          typeList:[],
          majorList:[],
          subjectList:[],
          questionKuList:[],
          levelList:[1,2,3,4,5],          
        };
    },

    methods: {
      updateAllow(q){
        this.modifyVisible = true;
        this.cForm=q;
        this.answerList = [];
        var answerArray = q.answer.split("duang");
        for(var i=0;i<answerArray.length;i++){
          this.answerList.push({content:answerArray[i]});
        }
      },
      // 关于修改试卷的几个bug
      addAnswer(){
        this.answerList.push({ content: ''});
      },
      removeAnswerItem(index){
        this.answerList.splice(index, 1);
      },
      //答案数组转换成字符串
      answerListShiftAnswerString(){
        var str ="";
        if(this.answerList){
          str+=this.answerList[0].content;
          for(var i=1;i<this.answerList.length;i++){
            var strItem = this.answerList[i].content;
            if(strItem){
              str+="duang"+strItem;
            }
          }
        }
        return str;
      },
      // 自动组卷，要求部分展示
      showMajor(major){
        var result=""
        for(var i in major){
          result += this.majorList[major[i]*1-1].major+';'
        }
        return result
      },
      showSubject(subject){
        var result=""
        for(var i in subject){
          result += this.subjectList[subject[i]*1-1].subject+';'
        }
        return result
      },
      showStores(storeIds){
        var result = ""
        for(var i in storeIds){
          for(var j in this.questionKuList){
            if(storeIds[i]==this.questionKuList[j].id){
              result += this.questionKuList[j].name + ';'
            }
          }
        }
        return result
      },
      showLevelBetween(row){
        if(row.level == 2)return "null"
        var result = "[";
        for(var i in row.levelBetween){
          result += row.levelBetween[i] +','
        }
        return result+']'
      },
      deleteRow(index, rows) {
        rows.splice(index, 1);
      },
      // 选择框多选
      handleClose(tag) {
        this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
      },

      showInput() {
        this.inputVisible = true;
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },

      handleInputConfirm() {
        let inputValue = this.inputValue;
        if (inputValue) {
          this.dynamicTags.push(inputValue);
        }
        this.inputVisible = false;
        this.inputValue = '';
      },
      // 计算试卷目前总分数
      countScore(){
        var totalScore = 0
        for(var i in this.allQuestionThisPaper){
          let questions = this.allQuestionThisPaper[i]
          for(var q in questions){
            totalScore += questions[q].score
          }
          this.totalScore = totalScore;
        }
      },
      // 是否可以修改
      // 当状态不对时，也不可以修改
      canModify(permissionId){
        if(permissionId == 3 || this.paper_info.status>=5)return false;
        else return true
      },

      // 添加一个类型的自动组卷
      addItem(){
        var o =Object.assign({}, this.intellectualExam) 
        o.level =''+ this.level
        if(o.level == 1){
          o.levelStartEnd = null
        }
        else{
          o.levelBetween = null
          o.levelStartEnd = []
          o.levelStartEnd.push(o.levelInterval.down)
          o.levelStartEnd.push(o.levelInterval.up)
        }
        this.getCountIntelligent(o)
      },

      // 查询自动组卷的情况是某存在，若存在数量是多少
      async getCountIntelligent(param){
        var num = param.number
        let result = await this.$API.exam_paper_management.getCountIntelligent(param);
        if(result.code==20000){
          var max = result.data.count;
          if(num>max){
            this.$message({
              type: "warning",
              message: "该限制条件下，题目数量只有"+max+"个，请更改数目或者条件",
            });
          }
          else 
          {
            this.intellectualExamList.push(param);
          }
        }
      },
      // 智能组卷
      async intelligentPaper(){
        var message = this.lander+"智能组卷"
        let result = await this.$API.exam_paper_management.intelligentPaper(this.intellectualExamList,this.paper_info.id,message);
        if(result.code==20000){
            this.getPageList();//重新更新题目的列表
            this.$message({
              type: "success",
              message: "智能组卷成功",
            });
        }
      },
      // 修改试卷
      modifyExamPaper(){
        this.modifyButtonVisible = !this.modifyButtonVisible
      },
      // 返回题目的类型
      questionType(q){
        // console.log(q)
        // console.log(this.typeList)
        for(var i in this.typeList){
          if(this.typeList[i].id == q){
            return this.typeList[i].type
          }
        }
      },
      // 获取所有已知的题目类型
      async getTypeList() {
        //获取专业分类的请求，不需要携带参数
        let result = await this.$API.question_management.reqGetTypeList();
        if(result.code==20000){
            this.typeList = result.data.typeList;
        }
      },
      async getMajorList() {
        //获取专业分类的请求，不需要携带参数
        let result = await this.$API.question_management.reqGetMajorList();
        if(result.code==20000){
            this.majorList = result.data.majorList;
        }
      },
      async getSubjectList() {
        //获取专业分类的请求，不需要携带参数
        let result = await this.$API.question_management.reqGetSubjectList();
        if(result.code==20000){
            this.subjectList = result.data.subjectList;
        }
      },
      async getQuestionKuList() {
        //获取专业分类的请求，不需要携带参数
        let result = await this.$API.question_management.reqGetQuestionKuList();
        if(result.code==20000){
            this.questionKuList = result.data.personalQuestionStores;
        }
      },
 
      // 获取试卷的所有信息
        async getPageList() {
            let result =
                await this.$API.exam_paper_management.getPaperInventory(this.paper_info.id);
            if (result.code == 20000) {
                this.allQuestionThisPaper = result.data.question; //试卷所有题目信息
                this.paperLog = result.data.logs; //试卷所有日志信息
                this.countScore()
            }
      },
   
      // 收到子控件返回的题目列表
      getListenEvent(msg,mark){
        this.selectedQuestions = msg;
        this.mark = mark;
        // 弹出对话框。然后展示试卷的名字，然后在后面输入这个题目对应的分数，最后才加入试卷中
        this.selectQuestionVisible = true;
      },

      // 将所有选中的题目导入到试卷中
      // 处理好所有题目对应的location之后再插入题目
      addSelectedQuestions(){
          // 首先先验证是不是每个题目都设定了分数
          var flag=0;  //0代表所有分数都设置了
          for(let i=0;i<this.selectedQuestions.length;i++){
            if(this.selectedQuestions[i].score==null){flag=1; this.$alert("您有题目未设置分数！");} 
          }
          // 整理好题目
          // 构建一个类，记录相关的类型的location。当选中的题目中有该类型时，才更新。
          var select = {};
          var Sdata = [];
          for(let j=0;j<this.selectedQuestions.length;j++){
            var type = this.selectedQuestions[j].type;
            if(select[type] == undefined ){
              // 没有该属性，在查询之后添加即可
              var location ;
              for(var k in this.typeList){
                if(this.typeList[k].type == type)
                {
                  location = this.findHowMany(this.typeList[k].id);
                  break;
                }
              }
              select[type] = parseFloat( location);
              Sdata.push({questionId: this.selectedQuestions[j].id,location: location,score: parseFloat( this.selectedQuestions[j].score)})
            }
            else{
              select[type] = parseFloat(select[type]+1.2)  //在上一个的基础上添加1
              Sdata.push({questionId: this.selectedQuestions[j].id,location:select[type],score: parseFloat( this.selectedQuestions[j].score)})
            }
          }
          if(flag == 0){
          // 然后再验证是私人题库还是总体库里面的，调用不同的函数，并且是循环调用
          if(this.mark!=''){
            // 私人题库
            // for(let i=0;i<this.selectedQuestions.length;i++)
            //   {
            //     this.addPersonalQuestionToPaper(this.selectedQuestions[i].id,this.selectedQuestions[i].type,this.selectedQuestions[i].score);
            //   }  
            var message = this.lander+"导入私人题库题目"
            this.addPersonalQuestionToPaper(Sdata,this.paper_info.id,message)
            }
          else{
            // 总体库
            // for(let i=0;i<this.selectedQuestions.length;i++){
            //     this.addWholeQuestionToPaper(this.selectedQuestions[i].id,this.selectedQuestions[i].type,this.selectedQuestions[i].score);
            //   }  
            var message = this.lander+"导入总题库题目"
            this.addWholeQuestionToPaper(Sdata,this.paper_info.id,message)
            }
          }
      },
      // 私人题库
      async addPersonalQuestionToPaper(param,paperId,message)
      {
        let result =
            await this.$API.exam_paper_management.addPaperQuestionFromPersonal(param,paperId,message);
        if (result.code == 20000) {
            this.getPageList();//重新更新题目的列表
            this.$message({
              type: "success",
              message: "私人题库导入题目成功",
            });
        }
        else{
          this.$message({
              type: "warning",
              message: "导入失败",
            });
        }
      },
      // 总题库
      async addWholeQuestionToPaper(param,paperId,message)
      {
        let result =
            await this.$API.exam_paper_management.addPaperQuestionFromTotal(param,paperId,message);
        if (result.code == 20000) {
            this.getPageList();//重新更新题目的列表
            this.$message({
              type: "success",
              message: "总题库导入题目成功",
            });
        }
        else{
          this.$message({
              type: "warning",
              message: "导入失败",
            });
        }        
      },
      // 私人题库导入
      // async addPersonalQuestionToPaper(personalQuestionId,type,score){
      //   var location;
        
      //   for(var i in this.typeList){
      //     if(this.typeList[i].type == type)
      //     {
      //       location = this.findHowMany(this.typeList[i].id);
            
      //       break;
      //     }
      //   }
      //   var paperId = this.paper_info.id;
      //   var message = this.lander+"从私人题库导入一道题目";
      //   let result =
      //       await this.$API.exam_paper_management.addPersonalQuestionToPaper(paperId,personalQuestionId,location,message, score);
      //   if (result.code == 20000) {
      //       this.getPageList();//重新更新题目的列表
      //       this.$message({
      //         type: "success",
      //         message: "私人题库导入题目成功",
      //       });
      //   }
      //   else{
      //     this.$message({
      //         type: "warning",
      //         message: "导入失败",
      //       });
      //   }
      // },

      // 总体库导入
      // 批量导入题目.同一种类型导入好几个，最后location判断的数字是一样的
      // async addWholeQuestionToPaper(questionId,type,score){
      //   var location;
      //   for(var i in this.typeList){
      //     if(this.typeList[i].type == type)
      //     {
      //       location = this.findHowMany(this.typeList[i].id);
      //       break;
      //     }
      //   }

      //   var paperId = this.paper_info.id;
      //   var message = this.lander+"从总题库导入一道题目";
      //   let result =
      //       await this.$API.exam_paper_management.addWholeQuestionToPaper(paperId,questionId,location,message,score);
      //   if (result.code == 20000) {
      //       this.getPageList();//重新更新题目的列表
      //       this.$message({
      //         type: "success",
      //         message: "总题库导入题目成功",
      //       });
      //   }
      //   else{
      //         this.$message({
      //         type: "warning",
      //         message: "导入失败",
      //       });
      //   }
      // },

      // 自定义添加题目，收集的信息有  PaperQuestion paperQuestion 题目, MultipartFile file 题目图片, String message 日志信息
      
      async addOneQuestion(question){
        question.paperId = this.paper_info.id;
        question.version = parseInt('0');
        question.score = parseFloat(question.score);
        question.location = parseFloat(question.location);

        var type = question.type; //获取题目的类型
        question.location = this.findHowMany(type);
        var message = this.lander+"添加一道题目";
        let result =
            await this.$API.exam_paper_management.addQuestionToPaper(question,message);

        if (result.code == 20000) {
            this.getPageList();//重新更新题目的列表
            this.$message({
              type: "success",
              message: "添加成功",
            });
        }
        else{
            this.$message({
              type: "warning",
              message: "添加失败",
            });
        }
      },

      //删除题目
      // 删除题目时，导致位置信息减少。所以题目的location不是等距离递增的。
      // String paperQuestionId, String message, String paperId
      async deleteQuestion(paperQuestionId){
        var paperId = this.paper_info.id;
        var message = this.lander+"删除一道题目";
        // deleteOnePaperQuestion
        let result =
            await this.$API.exam_paper_management.deleteOnePaperQuestion(paperQuestionId, message, paperId);

        if (result.code == 20000) {
            this.$message({
              type: "success",
              message: "删除成功",
            });
            this.getPageList();//重新更新题目的列表
        }
        else{
          this.$message({
              type: "warning",
              message: "删除失败",
            });
        }
      },
      //修改题目
      async modifyQuestion(question){
        // 将题目内容拼接好放入question的answer中
        if(this.cForm.type!='1'&&this.cForm.type!='2'&&this.cForm.type!='3'){
          question.answer = this.answerListShiftAnswerString();
        }
        // 题目的位置信息单独调整，该处只是修改其他信息
        // 弹出的消息框和新建题目时相同
        let result =
            await this.$API.exam_paper_management.updatePaperQuestion(question);

        if (result.code == 20000) {
            this.getPageList();//重新更新题目的列表
            this.$message({
              type: "success",
              message: "修改成功",
            });
        }
        else{
            this.$message({
              type: "warning",
              message: "修改失败",
            });
        }
      },

      // 将试卷提交审核
      async SubmitForApproval(){
        if(this.paper_info.status<3){
          this.$alert("试卷还未完工，不能提交审核！");
        }
        else{
          if(this.paper_info.status=='4'){
            this.$alert("您已提交审核，不能重复提交！");
          }
          else{
            let result =
            await this.$API.exam_paper_management.SubmitForApproval(this.paper_info.id);
              if (result.code == 20000) {
                this.$message({
                  type: "success",
                  message: "成功提交审核，请耐心等待审核结果",
                });
              }
              else{
                  this.$message({
              type: "warning",
              message: "提交审核失败",
            });
              }
          }

        }

      },

      // 找到这个类型的题目到底有多少个，决定添加题目时的location，不过根据最后一个题目的location上+1
      findHowMany(type)
      {
        for(var i in this.allQuestionThisPaper){
          if(type == i){//如果属性值相等，那么测量这个部分到底有多少题目
            var len = this.allQuestionThisPaper[i].length
            return (this.allQuestionThisPaper[i][len-1].location)*1+1; //添加题目的location设置
          }
        }
        return 0; //如果没有该类别，那么代表这个类别没有题目，location设置为0
      },

/*
      // 试卷题目像上移动
      async moveUp(type,j)
      {
        j = parseInt(j);
        // type是再allquestino中代表题目类型，j是代表该类型的第几个题目
        if(j==0){
          this.$message({
              type: "warning",
              message: "无法继续上移",
            });
        }
        else{
          var id1 = this.allQuestionThisPaper[type][j].id;
          var id2 = this.allQuestionThisPaper[type][j-1].id;
          var paperId = this.paper_info.id;
          var message = this.lander+"更改了题目的位置"
          // 下面交换题目的位置
          let result =
            await this.$API.exam_paper_management.updateLocation(id1, id2, paperId,message);

          if(result.code != 20000){
            this.$message({
              type: "warning",
              message: "移动失败",
            });
          }
          else{
            this.getPageList();//重新更新题目的列表
          }
        }
      },
      async moveDown(type,j){
        j = parseInt(j);
        // type是再allquestino中代表题目类型，j是代表该类型的第几个题目
        if(j==this.allQuestionThisPaper[type].length-1){
          this.$message({
              type: "warning",
              message: "无法继续下移",
            });
        }
        else{
          var id1 = this.allQuestionThisPaper[type][j].id;
          var id2 = this.allQuestionThisPaper[type][j+1].id;
          var paperId = this.paper_info.id;
          var message = this.lander+"更改了题目的位置"
          // 下面交换题目的位置
          let result =
            await this.$API.exam_paper_management.updateLocation(id1, id2, paperId,message);

          if(result.code != 20000){
            this.$message({
              type: "warning",
              message: "移动失败",
            });
          }
          else{
            this.getPageList();//重新更新题目的列表
          }
        }        
      },
*/
      // 调整位置
      changeLocation(){
        this.disabled = false;
        const h = this.$createElement;
        this.$message({
          message: h('p', null, [
            h('span', null, '拖拽题目即可更改位置'),
          ])  
        });
      },
    
      // 确定位置
      async confirmLocation(){
        this.disabled = true;
        var location = 0;
        var idLocation = []
        // 直接遍历该类型题目，然后从小到大重新设置location
        for(var i in this.allQuestionThisPaper){
          let questions = this.allQuestionThisPaper[i]
          location = 0
          for(var q in questions){
            questions[q].location = location
            location += 1
            var o = {paperQuestionId:questions[q].id,location:questions[q].location}
            idLocation.push(o)
          }
        }
        
        var message = this.lander+'更改位置题目';
        let result =
          await this.$API.exam_paper_management.confirmAllPaperQuestionLocation(idLocation,this.paper_info.id,message);
        if (result.code == 20000) {
          this.$message({
            type: "success",
            message: "调整位置成功",
          });
          
        }
        else{
            this.$message({
            type: "warning",
            message: "调整失败",
            });
        }
        

      },

      handleCommand(command){
        if(command =='1'){this.exportWord()}
        else if(command == '2'){this.exportWord2()}
      },
    // 导出word--通过模板
      exportWord() {
        // 首先将题目的形式变换以下
        var exportName = this.paper_info.name;
        var list = [];
        for(var i in this.allQuestionThisPaper){
          // 获取该题目类型
          var type = this.typeList[i-1].type
          list.push({
            type:type,
            content:this.allQuestionThisPaper[i]
          })
        }
        
        const _this = this
        JSZipUtils.getBinaryContent('index.docx', function(error, content) {
          // 抛出异常
          if (error) {
            throw error
          }
          // 创建一个JSZip实例，内容为模板的内容
          let zip = new JSZip(content)
          // 创建并加载docxtemplater实例对象
          let doc = new Docxtemplater().loadZip(zip)
          // 设置模板变量的值
          doc.setData({
            // ..._this.list,
            list: list,
            name:_this.paper_info.name,
            remark:_this.paper_info.remark
          })
          try {
            // 用模板变量的值替换所有模板变量
            doc.render()
          } catch (error) {
            this.$alert('导出报表失败')
            throw error
          }

          // 生成一个代表docxtemplater对象的zip文件（不是一个真实的文件，而是在内存中的表示）
          let out = doc.getZip().generate({
            type: 'blob',
            mimeType:
              'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
          })
          _this.$notify({
            title: '成功',
            message: '正在导出，请稍等片刻',
            type: 'success'
          });
          // 将目标文件对象保存为目标类型的文件，并命名
          saveAs(out, exportName+'.docx')
        })
      },

    // 导出word--通过数据流
    exportWord2() {
      var name = this.paper_info.name
      this.$notify({
        title: '成功',
        message: '正在导出，请稍等片刻',
        type: 'success'
      });
      setTimeout(function() {
        $('#pdf').wordExport(name)
      }, 300)
    },
}
}
</script>
<style lang="scss">
    .el-drawer.rtl{
    overflow: scroll
    }

    
.el-drawer__container ::-webkit-scrollbar{
    display: none;
}
</style>
<style scoped>
  .title{
    font-size: 19px;
    font: bold;
  }
  .item {
      padding: 6px 12px;
      margin: 0px 10px 0px 10px;
      border: solid 1px #eee;
      background-color: #f1f1f1;
      text-align: left;
  }      
  .item:hover {
      background-color: #fdfdfd;
      cursor: move;
  }
</style>